package jpa.dsl.boot.service.impl;

import jpa.dsl.boot.model2.TCity;
import jpa.dsl.boot.model2.generate.QTCity;
import jpa.dsl.boot.model2.generate.QTHotel;
import jpa.dsl.boot.service.CiTYService;
import com.querydsl.core.QueryResults;
import com.querydsl.core.Tuple;
import com.querydsl.core.types.Predicate;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;

/** https://www.jianshu.com/p/2b68af9aa0f5
 */
@Service
public class CityServiceImpl implements CiTYService {

    @Autowired
    private CityRepository cityRepository;
    @Autowired
    private JPAQueryFactory jpaQueryFactory;

    public Page<TCity> getPageByConditions(String cityName){
        QTCity qtCity = QTCity.tCity;
        //该Predicate为querydsl下的类,支持嵌套组装复杂查询条件
        Predicate predicate = qtCity.id.longValue().lt(3)
                .and(qtCity.name.like(cityName));
        //分页排序
        Sort sort = new Sort(new Sort.Order(Sort.Direction.ASC,"id"));
        PageRequest pageRequest = new PageRequest(0,10,sort);
        //查找结果
        Page<TCity> tCityPage = cityRepository.findAll(predicate,pageRequest);
        return tCityPage;
    }

    //关联查询示例,查询出城市和对应的旅店
    public List<Tuple> findCityAndHotel(Predicate predicate) {
//        JPAQueryFactory queryFactory = new JPAQueryFactory(em);
        JPAQuery<Tuple> jpaQuery =
                jpaQueryFactory.select(QTCity.tCity, QTHotel.tHotel)
                        .from(QTCity.tCity)
                        .leftJoin(QTHotel.tHotel)
                        .on(QTHotel.tHotel.city.longValue().eq(QTCity.tCity.id.longValue()))
                        .where(predicate);
        return jpaQuery.fetch();
        //对多元组取出数据,这个和select时的数据相匹配
//        for (Tuple row : result) {
//            System.out.println("qtCity:"+row.get(qtCity));
//            System.out.println("qtHotel:"+row.get(qtHotel));
//            System.out.println("--------------------");
//        }
    }

    public QueryResults<Tuple> findCityAndHotelPage(Predicate predicate, Pageable pageable) {
//        JPAQueryFactory queryFactory = new JPAQueryFactory(em);
        JPAQuery<Tuple> jpaQuery = jpaQueryFactory.select(QTCity.tCity.id,QTHotel.tHotel)
                .from(QTCity.tCity)
                .leftJoin(QTHotel.tHotel)
                .on(QTHotel.tHotel.city.longValue().eq(QTCity.tCity.id.longValue()))
                .where(predicate)
                .offset(pageable.getOffset())
                .limit(pageable.getPageSize());
        //拿到分页结果
        return jpaQuery.fetchResults();
    }



}
